package org.common.users.config;

import org.common.users.intercepter.AnnotationTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public AnnotationTokenInterceptor tokenInterceptor() {
        return new AnnotationTokenInterceptor();
    }

    /**
     * 解决http请求跨域问题
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //允许哪些域访问
        //String[] allowedOrigins = {"http://localhost:9001", "http://localhost:9002", "http://localhost:9003","http://localhost:8000"};
        registry.addMapping("/*").
                allowedOrigins("*").
                allowCredentials(true).
                allowedHeaders("Origin, X-Requested-With, Content-Type, Accept").
                allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS").maxAge(3600);//访问超时时间：一小时
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        // TODO Auto-generated method stub

    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // TODO Auto-generated method stub
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }


    /**
     * 配置消息转换器
     * @param converters
     */
    /*@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //添加fastJson的配置信息;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //全局时间配置
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //在convert中添加配置信息.
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(0,fastConverter);
    }*/

}
